package com.wu.server.service;

import com.wu.server.Thread.MainThread;
import com.wu.server.code.Code;
import com.wu.server.dao.NewTypeRepository;
import com.wu.server.entity.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class TypeServer {
    @Autowired
    NewTypeRepository typeRepository;
    @Autowired
    Code code;
    @Autowired
    TypeTopServer typeTopServer;
    public Object queryType(String id, String typeName,String summaryRange,String salesRange,String order,String sort,int pageNum,int pageSize){
        String typeQuery = "%"+typeName+"%";
        String[] summaryRangeQuery = summaryRange.split(",");
        String[] salesRangeQuery = salesRange.split(",");
        String typeIdQuery = !id.equals("") ? id : null;//  模糊查询
        Pageable pageable = PageRequest.of(pageNum - 1,pageSize, Sort.Direction.fromString(order),sort);
        Page<Type> type = typeRepository.findAllBy(typeIdQuery,typeQuery,summaryRangeQuery[0],summaryRangeQuery[1],salesRangeQuery[0],salesRangeQuery[1],pageable);
        List<Type> data = type.getContent();
        HashMap<String,Object> paging = new HashMap<>();
        paging.put("total",type.getTotalElements());
        paging.put("pageNum",type.getNumber()+1);
        paging.put("pageSize",type.getSize());
        HashMap<String,Object> result = new HashMap<>();
        result.put("paging",paging);
        result.put("data",data);
        return code.getMeta(Code.SUCCESS,result);
    }

    public Object addType(Type type){
        try{
            typeRepository.save(type);
            typeTopServer.sendData();
            return code.getMeta(Code.SUCCESS,type);
        }catch (Exception e){
            return code.getMeta(Code.creatFail, null);
        }
    }
    public Object updateType(Type type){
        try{
            typeRepository.save(type);
            typeTopServer.sendData();
            return code.getMeta(Code.SUCCESS,type);
        }catch (Exception e){
            return code.getMeta(Code.updateFail, null);
        }
    }
    public Object deleteType(int id){
        try{
            typeRepository.deleteTypeById(id);
            typeTopServer.sendData();
            return code.getMeta(Code.SUCCESS,id);
        }catch (Exception e){
            return code.getMeta(Code.deleteFail, null);
        }
    }
}
